//////////////////////////////////////////////////////////////////////////
#include "ManagedImageConverter.h"
//////////////////////////////////////////////////////////////////////////
#pragma once
//////////////////////////////////////////////////////////////////////////
using namespace System::Windows::Forms;
using namespace System::Drawing;
//////////////////////////////////////////////////////////////////////////
NAMESPACE_BEGIN_UI
//////////////////////////////////////////////////////////////////////////
public ref class ImageViewer : public Control
{
private:
	static RectangleF RectangleToRectangleF(Rectangle rect)
	{
		return RectangleF((float)rect.X, (float)rect.Y, (float)rect.Width, (float)rect.Height);
	}

	static Rectangle RectangleFToRectangle(RectangleF rect)
	{
		return Rectangle((int)rect.X, (int)rect.Y, (int)rect.Width, (int)rect.Height);
	}


public:
	ImageViewer(void);

protected:
	/// <summary>
	/// Clean up any resources being used.
	/// </summary>
	~ImageViewer()
	{
		if (components != nullptr)
		{
			delete components;
		}
	}

	virtual void OnPaint(PaintEventArgs^ pe) override;
	void AdjustSize()
	{
		if (m_emPictureBoxSizeMode == PictureBoxSizeMode::AutoSize)
		{
			this->ClientSize = m_refImage == nullptr ? System::Drawing::Size::Empty : System::Drawing::Size(m_refImage->Width, m_refImage->Height);
		}
	}

private:
	/// <summary>
	/// Required designer variable.
	/// </summary>
	System::ComponentModel::IContainer^ components;

	/// <summary>
	/// Required method for Designer support - do not modify 
	/// the contents of this method with the code editor.
	/// </summary>
private:
	void InitializeComponent()
	{
		components = gcnew System::ComponentModel::Container();
	}

public:
	property PictureBoxSizeMode SizeMode
	{
		PictureBoxSizeMode get() { return m_emPictureBoxSizeMode; }
		void set(PictureBoxSizeMode mode) 
		{
			if (m_emPictureBoxSizeMode != mode)
			{
				m_emPictureBoxSizeMode = mode;
				AdjustSize();
				this->Invalidate();
			}
		}
	}

	property ManagedArr^ Image
	{
		void set(ManagedArr^ img)
		{
			m_refSource = img;
			m_refImage = ManagedImageConverter::Convert(m_refSource, m_refImage, m_refPalette);
			AdjustSize();
			this->Invalidate();
		}
	}

	property array<Color>^ Palette
	{
		array<Color>^ get() { return m_refPalette; }
		void set(array<Color>^ value)
		{
			m_refPalette = value;
			m_refImage = ManagedImageConverter::Convert(m_refSource, m_refImage, m_refPalette);
			this->Invalidate();
		}
	}

private:
	PictureBoxSizeMode			m_emPictureBoxSizeMode;
	array<Color>^				m_refPalette;
	Bitmap^						m_refImage;
	ManagedArr^					m_refSource;
};
//////////////////////////////////////////////////////////////////////////
NAMESPACE_END_UI
//////////////////////////////////////////////////////////////////////////